package com.mainbo.modular.system.controller.user;

import cn.stylefeng.roses.core.base.controller.BaseController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mainbo.core.util.Result;
import com.mainbo.jms.MessageTypes;
import com.mainbo.modular.jms.JmsService;
import com.mainbo.modular.jms.model.PeopleStudentMessageVo;
import com.mainbo.modular.jms.model.PeopleStudentVo;
import com.mainbo.modular.system.model.PtClass;
import com.mainbo.modular.system.model.PtOrg;
import com.mainbo.modular.system.model.Student;
import com.mainbo.modular.system.model.meta.MetaUtils;
import com.mainbo.modular.system.model.meta.vo.Meta;
import com.mainbo.modular.system.service.IPtClassService;
import com.mainbo.modular.system.service.IPtOrgService;
import com.mainbo.modular.system.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import com.mainbo.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;
import com.mainbo.modular.system.model.PtPeopleStudent;
import com.mainbo.modular.system.service.IPtPeopleStudentService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 控制器
 *
 * @author fengshuonan
 * @Date 2020-03-02 11:53:01
 */
@Controller
@RequestMapping("/ptPeopleStudent")
public class PtPeopleStudentController extends BaseController {
    private static  final Logger logger= LoggerFactory.getLogger(PtPeopleController.class);

    private String PREFIX = "/system/ptPeopleStudent/";

    @Resource
    private IPtPeopleStudentService ptPeopleStudentService;
    @Resource
    private IPtOrgService orgService;
    @Resource
    private JmsService jmsService;
    @Resource
    private StudentService studentService;
    @Resource
    private IPtClassService classService;

    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index(String peopleId,String orgId,Model model) {
        model.addAttribute("peopleId",peopleId);
        model.addAttribute("orgId",orgId);
        return PREFIX + "ptPeopleStudent.html";
    }

    /**
     * 跳转到添加
     */
    @RequestMapping("/ptPeopleStudent_add")
    public String ptPeopleStudentAdd(String peopleId, String orgId, Model model) {
        model.addAttribute("peopleId", peopleId);
        model.addAttribute("orgId", orgId);
        PtOrg org = orgService.selectById(orgId);
        // 学校的学段集合
        List<Meta> phaseList = MetaUtils.getOrgTypeProvider().listAllPhase(org.getSchoolings());
        // 学校的学段-年级map
        model.addAttribute("phaseList", phaseList);
        return PREFIX + "ptPeopleStudent_add.html";
    }

    /**
     * 跳转到修改
     */
    @RequestMapping("/ptPeopleStudent_update")
    public String ptPeopleStudentUpdate(PtPeopleStudent peopleStudent, Model model) {
        PtPeopleStudent ptPeopleStudent = ptPeopleStudentService.selectById(peopleStudent.getId());
        model.addAttribute("item",ptPeopleStudent);
        if (com.mainbo.utils.StringUtils.isNotBlank(peopleStudent.getClassId())) {
            PtClass classInfo = classService.selectById(peopleStudent.getClassId());
            Meta meta = MetaUtils.getMeta(classInfo.getGradeId());
            model.addAttribute("classInfo", classInfo);
            model.addAttribute("meta", meta);
        }
        PtOrg org = orgService.selectById(ptPeopleStudent.getOrgId());
        // 学校的学段集合
        List<Meta> phaseList = MetaUtils.getOrgTypeProvider().listAllPhase(org.getSchoolings());
        // 学校的学段-年级map
        model.addAttribute("phaseList", phaseList);
        LogObjectHolder.me().set(ptPeopleStudent);
        return PREFIX + "ptPeopleStudent_edit.html";
    }

    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(PtPeopleStudent ptPeopleStudent) {
        return ptPeopleStudentService.findAll(ptPeopleStudent);
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(PtPeopleStudent ptPeopleStudent) {
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        try {
            if (ptPeopleStudent.getId() != null) {
                PtPeopleStudent old = ptPeopleStudentService.selectById(ptPeopleStudent.getId());
                if (old.getStudentId().equals(ptPeopleStudent.getStudentId())){
                    Student student=studentService.selectById(ptPeopleStudent.getStudentId());
                    ptPeopleStudent.setStudentName(student.getName());
                }
                ptPeopleStudentService.updateById(ptPeopleStudent);
                this.sendMessage(MessageTypes.PEOPLE_STUDENT_UPDATE, ptPeopleStudent.selectById(ptPeopleStudent.getId()));
                result.setMsg("更新成功！");
                //LoggerUtils.updateLogger(LoggerModule.YHGL, "用户管理——修改家长子女关系，家长用户ID：{}", peoples.getId());
            } else {
                if (StringUtils.isNotBlank(ptPeopleStudent.getStudentId())){
                    Student student=studentService.selectById(ptPeopleStudent.getStudentId());
                    ptPeopleStudent.setStudentName(student.getName());
                }
                ptPeopleStudent.setCrtDttm(new Date());
                ptPeopleStudentService.insert(ptPeopleStudent);
                this.sendMessage(MessageTypes.PEOPLE_STUDENT_ADD, ptPeopleStudent);
                //LoggerUtils.insertLogger(LoggerModule.YHGL, "用户管理——添加家长子女关系，家长用户ID：{}", save.getId());
                result.setMsg("添加成功！");
            }
        } catch (Exception e) {
            result.setMsg("保存失败！");
            result.setCode(Result.FAIL);
            logger.error("家长子女保存失败", e);
        }
        return result;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete/{id}")
    @ResponseBody
    public Result delete(@PathVariable String id) {
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        try {
            PtPeopleStudent peopleStudent = ptPeopleStudentService.selectById(id);
            ptPeopleStudentService.deleteById(id);
            this.sendMessage(MessageTypes.PEOPLE_STUDENT_DELETE, peopleStudent);
            result.setMsg("删除成功！");
        } catch (Exception e) {
            result.setMsg("删除失败！");
            result.setCode(Result.FAIL);
            logger.error("家长子女删除失败", e);
        }
        return result;
    }


    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{ptPeopleStudentId}")
    @ResponseBody
    public Object detail(@PathVariable("ptPeopleStudentId") Integer ptPeopleStudentId) {
        return ptPeopleStudentService.selectById(ptPeopleStudentId);
    }

    /**
     * @param type
     *          类型
     * @param ps
     *          学生家长
     */
    public void sendMessage(MessageTypes type, PtPeopleStudent ps) {
        try {
            PeopleStudentMessageVo vo = new PeopleStudentMessageVo();
            vo.setMessageType(type.name());
            PeopleStudentVo peopleStudentVo = new PeopleStudentVo();
            BeanUtils.copyProperties(ps, peopleStudentVo);
            vo.setPeopleStudentVo(peopleStudentVo);
            jmsService.sendMessage(vo);
        } catch (Exception e) {
            logger.error("发送消息失败，消息类型{}", type.name(), e);
        }

    }
}
